package com.yellow.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.yellow.constant.MessageConstant;
import com.yellow.constant.RedisMessageConstant;
import com.yellow.enity.Result;
import com.yellow.pojo.Member;
import com.yellow.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @RequestMapping("/login")
    public Result login(@RequestBody  Map map, HttpServletResponse response) {
        //比较验证码
        String code = (String) map.get("validateCode");
        if (code == null) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        String telephone = (String) map.get("telephone");
        String code_servier = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (code_servier == null) {
            //验证码过期
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        if (code.equals(code_servier)) {
            //验证码正确
            //判断是否是会员 ,一个手机号只能注册一个用户
            Member member = memberService.findMemberByTelNum(telephone);
            if (member == null) {
                //自动注册会员
                member = new Member(telephone, new Date());
                memberService.add(member);

            }
            //发送cookie,内容未手机号,有效时间未30天
            Cookie cookie = new Cookie("login_member_telephone", telephone);
            //30天
            cookie.setMaxAge(60 * 60 * 24 * 30);
            //路径
            cookie.setPath("/");
            response.addCookie(cookie);
            //会员信息保存在redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone, 60 * 30, json);

            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        } else {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }

}
